//
//  DDContactInfosView.m
//  PrivateCloud
//
//  Created by mars on 13-10-28.
//  Copyright (c) 2013年 sarah doo. All rights reserved.
//

#import "DDContactInfosView.h"
#import "DDContactInfo.h"
#import "DDSeverTableModel.h"
#import "DDSeverTableCell.h"
#import "DDSuccessViewController.h"
#import "DDSeverViewController.h"
#import "DDAddressBookUtils.h"
#import "TestAddressBook.h"
#import "DDUploadAddressBook.h"
#import "DDVerifyThread.h"
#import "IOOperation.h"
#import "UIColor+.h"
#import "DDCommentDic.h"

#define ALL_SELECT_TAG 10000
@implementation DDContactInfosView
@synthesize resultArray, table,titleName,type,fileDataSource,from;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [[UIApplication sharedApplication] setIdleTimerDisabled: YES];
    [super viewDidLoad];
    isAllSelect = NO;
    self.resultArray = [[NSMutableArray alloc]init];

    for (DDContactInfo* info in fileDataSource) {
        DDContactModel* model = [[DDContactModel alloc]init];
        model.name = info.name;
        model.email = info.email;
        if ([info.phoneNums count] > 0) {
            model.mobileNo = [info.phoneNums objectAtIndex:0];
        }
        else{
            model.mobileNo = @"";
        }
        if ([info.homeNums count] > 0) {
            model.homeNo = [info.homeNums objectAtIndex:0];
        }
        else{
            model.homeNo = @"";
        }
        if ([info.workNums count]>0) {
            model.workNo = [info.workNums objectAtIndex:0];
        }
        else{
            model.workNo = @"";
        }
        if ([info.iphoneNums count] > 0) {
            model.iphoneNo = [info.iphoneNums objectAtIndex:0];
        }
        else{
            model.iphoneNo = @"";
        }
        [self.resultArray addObject:model];
        [model release];
    }
    [self createTopView];
}


- (void)createTopView {
    UIView *linkView = [[UIView alloc] initWithFrame:CGRectMake(0, 20, self.view.frame.size.width, 40)];
    linkView.backgroundColor = [UIColor colorWithString:@"#273826"];
    UIButton *backButton = [UIButton buttonWithType:UIButtonTypeCustom];
    UIImage *image = [UIImage imageNamed:@"ico_back.png"];
    backButton.frame = CGRectMake(10, 4, 32, 32);
    [backButton addTarget:self action:@selector(backButtonPressed:) forControlEvents:UIControlEventTouchUpInside];
    [backButton setImage:image forState:UIControlStateNormal];
    [linkView addSubview:backButton];
    UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(self.view.frame.size.width/2-50, 5, self.view.frame.size.width - image.size.width - 80, 30)];
    label.font = [UIFont systemFontOfSize:15];
//    NSString* titleName = nil;
    if (type == SERVER_CODE) {
        titleName = @"服务器通讯录";
    }
    else{
        titleName = @"本地通讯录";
    }
    label.text = titleName;
    label.textColor = [UIColor whiteColor];
    [linkView addSubview:label];
    [label release];
    [self.view addSubview:linkView];
    
    UIButton *freshButton = [UIButton buttonWithType:UIButtonTypeCustom];
    freshButton.frame = CGRectMake(self.view.frame.size.width - 50, 0, 80, 30);
    freshButton.backgroundColor = [UIColor clearColor];
    UILabel *buttonLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 5, freshButton.frame.size.width, freshButton.frame.size.height)];
    buttonLabel.textColor = [UIColor whiteColor];
    buttonLabel.font = [UIFont systemFontOfSize:15];
    buttonLabel.backgroundColor = [UIColor clearColor];
    buttonLabel.text = @"全选";
    buttonLabel.tag = ALL_SELECT_TAG;
    [freshButton addTarget:self action:@selector(selectAllItem:) forControlEvents:UIControlEventTouchUpInside];
    [freshButton addSubview:buttonLabel];
    [buttonLabel release];
    [linkView addSubview:freshButton];
    [linkView release];
    
    self.table = [[UITableView alloc] initWithFrame:CGRectMake( 5, 60, self.view.frame.size.width - 10, self.view.frame.size.height - 120) style:UITableViewStylePlain];
    self.table.delegate = self;
    table.dataSource = self;
    [self.view addSubview:table];
    //    [tableView release];
    UIView *footerView = [[UIView alloc] initWithFrame:CGRectMake(0, self.view.frame.size.height - 50, self.view.frame.size.width, 50)];
    [footerView setBackgroundColor:[UIColor blackColor]];
    [self.view addSubview:footerView];
    
    UIButton *sureButton = [UIButton buttonWithType:UIButtonTypeCustom];
    sureButton.frame = CGRectMake(0, 0, self.view.frame.size.width, 50);
    sureButton.backgroundColor = [UIColor clearColor];
    UILabel *sureLabel = [[UILabel alloc] initWithFrame:CGRectMake(footerView.frame.size.width/2 - 25, 0, footerView.frame.size.width, footerView.frame.size.height)];
    sureLabel.textColor = [UIColor whiteColor];
    sureLabel.font = [UIFont systemFontOfSize:15];
    sureLabel.backgroundColor = [UIColor clearColor];
    sureLabel.text = @"确   定";
    [sureButton addTarget:self action:@selector(sureButtonPressed:) forControlEvents:UIControlEventTouchUpInside];
    [sureButton addSubview:sureLabel];
    [sureLabel release];
    [footerView addSubview:sureButton];
    [footerView release];
}

#pragma sure button
//确定按钮被点击的情况
- (void)sureButtonPressed:(id)sender {
    //确认哪些联系人信息被选中
    NSMutableArray* selectedContactInfos = [[NSMutableArray alloc]init];
    for (int i = 0; i < [self.resultArray count]; i++) {
        DDContactModel* contactModel = [self.resultArray objectAtIndex:i];
        if(contactModel.isSelected){
            [selectedContactInfos addObject:[self.fileDataSource objectAtIndex:i]];
        }
    }
    
    if ([selectedContactInfos count] == 0) {
        return;
    }
    //这里需要判断当前的状态，如果是服务器状态，需要将数据保存至本地通讯录，然后再重新的加载数据
    if(type == SERVER_CODE){
        DDAddressBookUtils* bookUtils = [[DDAddressBookUtils alloc]init];
        
//        [self showProgressDialogWithCode:SERVER_CODE];
        
        progressHUD = [[MBProgressHUD alloc] initWithView:self.view];
        [self.view addSubview:progressHUD];
        
        // Regiser for HUD callbacks so we can remove it from the window at the right time
        progressHUD.delegate = self;
        // Show the HUD while the provided method executes in a new thread
        //[HUD showWhileExecuting:@selector(myTask) onTarget:self withObject:nil animated:YES];
        [progressHUD show:YES];
        progressHUD.labelText=@"正在导入联系人";
        progressHUD.mode = MBProgressHUDModeIndeterminate;
        TestAddressBook* testAddressBook = [[TestAddressBook alloc]init];
        for (DDContactInfo* info in selectedContactInfos) {
            BOOL flag = [testAddressBook isContactInfoExist:info];
            if(!flag){
                ABAddressBookRef addressBook = ABAddressBookCreate();
                [bookUtils createNewPersonWithAddressBook:addressBook andPerson:info];
            }
        }
        [progressHUD hide:YES];
        
        progressHUD = [[MBProgressHUD alloc] initWithView:self.view];
        [self.view addSubview:progressHUD];
        UITextView* textView = [[UITextView alloc]init];
        textView.text=@"导入完毕";
        progressHUD.delegate = self;
        progressHUD.mode = MBProgressHUDModeCustomView;
        progressHUD.labelText=@"导入完毕";
        [progressHUD show:YES];
        [progressHUD hide:YES afterDelay:3];

    }
    //如果是客户端状态，则需要生成通讯录vcf文件，并且进行上传
    else{
        
        //开启上传进度条
        
        progressHUD = [[MBProgressHUD alloc] initWithView:self.view];
        [self.view addSubview:progressHUD];
        progressHUD.delegate = self;
        [progressHUD show:YES];
        progressHUD.labelText=@"正在上传联系人";
        progressHUD.mode = MBProgressHUDModeIndeterminate;
        
        TestAddressBook* testAddressBook = [[TestAddressBook alloc]init];
        [testAddressBook createVcfWithContactInfos:selectedContactInfos atPath:@"local_temp.vcf"];
        IOOperation* op = [[IOOperation alloc]init];
        long length = [op getVcardFileLength:@"local_temp.vcf"];
        DDUploadAddressBook* uploadAddressBook = [[DDUploadAddressBook alloc]initWithFileSize:length];
        [[DDVerifyThread sharedVerifyThread] setUploadBookCallback:self];
        [[DDVerifyThread sharedVerifyThread]setUploadVcfFlag:YES];
        [[DDVerifyThread sharedVerifyThread]sendMessage:uploadAddressBook];
        
        
    }

}

//- (void)showProgressDialog{
//    bgView = [[UIView alloc] initWithFrame:self.view.frame];
//    [self.view addSubview:bgView];
//    bgView.backgroundColor = [UIColor blackColor];
//    bgView.alpha = 0.8;
//    bgView.userInteractionEnabled = NO;
//    [self.view bringSubviewToFront:bgView];
//    progress = [MBProgressHUD showHUDAddedTo:bgView animated:YES];
//    progress.mode = MBProgressHUDModeIndeterminate;
//    progress.opacity = 0.6;
//    progress.labelFont = [UIFont boldSystemFontOfSize:14];
//    progress.detailsLabelFont = [UIFont boldSystemFontOfSize:12];
//    progress.detailsLabelText =  @"正在下载数据..";
//    
//    
//}
//
//- (void)dismisProgressDialog{
//    progress.hidden = YES;
//    [bgView removeFromSuperview];
//}

#pragma - mark tableViewDelegate

//返回当前列表对象的个数
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return [resultArray count];
}

//每次创建一个子View时，会运行该方法
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    NSString *cellID = @"cellID";
    //DDSeverTableCell *cell = [[[DDSeverTableCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellID] autorelease];
    //DDContactCell* cell = [[[DDContactCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellID]autorelease];
    DDContactCell* cell = [tableView dequeueReusableCellWithIdentifier:cellID];
    if (cell == nil)
    {
        cell = [[[DDContactCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellID] autorelease];
    }
    cell.model = [self.resultArray objectAtIndex:indexPath.row];
    //    cell.nameLabel.text = @"test";
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:NO];
    DDContactModel* curModel = [self.resultArray objectAtIndex:indexPath.row];
    curModel.isSelected = !curModel.isSelected;
    [self.resultArray removeObjectAtIndex:indexPath.row];
    [self.resultArray insertObject:curModel atIndex:indexPath.row];
    [tableView reloadData];
    
}

- (void)backButtonPressed:(id)sender {
    if (type == LOCAL_CODE) {
        DDSuccessViewController* success = [[DDSuccessViewController alloc]initWithNibName:nil bundle:nil];
        [self presentViewController:success animated:NO completion:nil];
        [success release];
    }
    else{
        DDSeverViewController *sever = [[DDSeverViewController alloc] initWithNibName:nil bundle:nil];
        [self presentViewController:sever animated:NO completion:nil];
        [sever release];
    }
}
- (void)selectAllItem:(id)sender {
    NSArray *array = [NSArray arrayWithArray:self.resultArray];
    UILabel* buttonLabel = [self.view viewWithTag:ALL_SELECT_TAG];
    if (!isAllSelect) {
        [self.resultArray removeAllObjects];
        for (int i = 0; i < [array count]; i++) {
            DDSeverTableModel *model = [array objectAtIndex:i];
            model.isSelected = YES;
            [self.resultArray addObject:model];
        }
        isAllSelect = YES;
        buttonLabel.text = @"取消";
        [table reloadData];
    } else {
        [self.resultArray removeAllObjects];
        for (int i = 0; i < [array count]; i++) {
            DDSeverTableModel *model = [array objectAtIndex:i];
            model.isSelected = NO;
            [self.resultArray addObject:model];
        }
        isAllSelect = NO;
        buttonLabel.text = @"全选";
        [table reloadData];
    }
    
}

-(void)uploadBookComplete{
    [progressHUD hide:YES];
    
    progressHUD = [[MBProgressHUD alloc] initWithView:self.view];
    [self.view addSubview:progressHUD];
    UITextView* textView = [[UITextView alloc]init];
    textView.text=@"上传完毕";
    progressHUD.delegate = self;
    progressHUD.mode = MBProgressHUDModeCustomView;
    progressHUD.labelText=@"上传完毕";
    [progressHUD show:YES];
    [progressHUD hide:YES afterDelay:3];
}



- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 100;
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

//- (void)hudWasHidden:(MBProgressHUD *)hud {
//	// Remove HUD from screen when the HUD was hidded
//	[progressHUD removeFromSuperview];
//	[progressHUD release];
//	progressHUD = nil;
//}

@end
